<script setup>
import { ref, reactive, computed } from 'vue'
import ImageCode from '@/components/image-code/index.vue'
import { useRouter, useRoute } from 'vue-router'
import { randomString } from '@/utils/index.js'
import useUserStore from '@/stores/user.js'
import { ElMessage } from 'element-plus'
import useThemeStore from '@/stores/theme.js'

const loginForm = ref(null)
const data = reactive({
  username: '',
  password: '',
  img_code: '',
  category: 1,
})
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const themeStore = useThemeStore()
const loading = ref(false)
const emit = defineEmits('login')
let imageErrCount = 0
const imageCodeLength = 4
const imageStr = ref(randomString(imageCodeLength))
const changeImageStr = () => {
  imageStr.value = randomString(imageCodeLength)
}

const usernameErrorMessage = computed(() => {
  return data.category === 1 ? '学号' : '工号'
})

const validateImageStr = (rule, value, callback) => {
  if (value.toLowerCase() !== imageStr.value.toLowerCase()) {
    if (imageErrCount < 3) {
      imageErrCount++
    } else {
      changeImageStr()
      imageErrCount = 0
    }
    return callback(new Error('验证码不正确'))
  }
  return callback()
}

const validateUsername = (rule, value, callback) => {
  if (value.trim() === '') {
    return callback(new Error('请输入' + usernameErrorMessage.value))
  }
  return callback()
}

const rules = {
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }],
  img_code: [
    { required: true, message: '请输入图片验证码', trigger: 'blur' },
    { validator: validateImageStr, trigger: 'blur' },
  ],
}

const handleLogin = async (formEl) => {
  const valid = await formEl.validate((valid) => valid)
  if (!valid) return
  loading.value = true
  const login_result = await userStore.setLogin({ ...data })
  loading.value = false
  if (!login_result) return
  if (login_result === "bind") {
    show_bind.value = true
    return
  }
  // const redirect = ref(route.query && route.query.redirect)
  // await router.push(redirect.value ? redirect.value : '/')
  emit('login')
  ElMessage.success('登录成功')
}
</script>

<template>
  <div
    class="vw-100 login-container flex justify-content-center align-items-center"
  >
    <div class="login-body">
      <el-form
        ref="loginForm"
        class="login-form padding-15 border-radius-xl"
        :rules="rules"
        :label-width="0"
        :model="data"
      >
        <el-form-item class="pw-100">
          <el-radio-group
            v-model="data.category"
            class="padding-left-30 font-size"
          >
            <el-radio :value="1" size="large" class="w-100">我是学生</el-radio>
            <el-radio :value="2" size="large" class="w-100">我是老师</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            size="large"
            clearable
            :placeholder="`输入${usernameErrorMessage}`"
            v-model="data.username"
            prefix-icon="User"
            @keyup.native.enter="handleLogin(loginForm)"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            size="large"
            clearable
            :placeholder="`输入登录密码`"
            v-model="data.password"
            prefix-icon="Lock"
            @keyup.native.enter="handleLogin(loginForm)"
          />
        </el-form-item>
        <el-form-item prop="img_code">
          <el-input
            size="large"
            clearable
            placeholder="输入图片验证码"
            v-model="data.img_code"
            prefix-icon="Picture"
            class="pw-60"
            @keyup.native.enter="handleLogin(loginForm)"
          />
          <image-code
            class="margin-left-26 border-radius-xs"
            :identify-code="imageStr"
            @click="changeImageStr"
            :content-width="126"
            :content-height="38"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="large"
            type="primary"
            class="pw-100 margin-top-20"
            @click="handleLogin(loginForm)"
            :loading="loading"
            >登 录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style scoped lang="scss">
.login-container {
  height: 360px !important;
  //   background: var(--el-bg-color-page);
  //   background-color: pink;
  //   transition: color 0.2s, background-color 0.2s;
  .login-body {
    width: 500px;
    .login-form {
      transition: color 0.2s, background-color 0.2s;
      background: var(--el-bg-color-overlay);
    }
  }
}
</style>
